#include<iostream>
#include<vector>
using namespace std;
  
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
 
class Solution {
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        TreeNode* thead = nullptr;
        TreeNode* pcur = nullptr;
        for (auto digit : nums) {
            if (thead == nullptr)
                thead = new TreeNode(digit);
            else {
                while (pcur) {
                    if (pcur->val >= digit) {
                        if (pcur->left == nullptr) {
                            pcur->left = new TreeNode(digit);
                            break;
                        }
                        else pcur = pcur->left;
                    }
                    else if (pcur->val < digit) {
                        if (pcur->right == nullptr) {
                            pcur->right = new TreeNode(digit);
                            break;
                        }
                        else pcur = pcur->right;
                    }
                }
            }
            pcur = thead;
        }
        return thead;
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    TreeNode* _sortArrayToBST(int begin, int end, vector<int>& nums)
    {
        if (begin > end) return nullptr;
        int midPos = (begin + end) / 2;
        TreeNode* pmid = new TreeNode(nums[midPos]);
        pmid->left = _sortArrayToBST(begin, midPos - 1, nums);
        pmid->right = _sortArrayToBST(midPos + 1, end, nums);
        return pmid;
    }

public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return _sortArrayToBST(0, nums.size() - 1, nums);
    }
};